/*
 * @Description: 异步状态刷新
 * @Author: chenju
 * @Date: 2022-11-14 10:13:04
 * @LastEditors: chenju
 * @LastEditTime: 2022-12-14 14:05:45
 */
import { ref, Ref, onUnmounted } from 'vue';

interface UseAsyncStatusRefreshResult {
  // 最终的状态（过程中true，没异步任务或者任务完成false）
  refreshStatus: Ref<boolean>;
  // 开始刷新异步状态的方法
  handleStartRefresh: (type?: string) => void;
}

/**
 * 异步状态刷新
 * @param statusRefreshApi 接口请求方法，返回值为Promise<boolean>
 * @param successCallback 刷新成功后的回调方法
 * @returns
 */
export const useAsyncStatusRefresh = (
  statusRefreshApi: () => Promise<boolean>,
  successCallback: (type: string) => void
): UseAsyncStatusRefreshResult => {
  // 状态
  const refreshStatus = ref<boolean>(false);
  // 是否需要刷新
  const needShowMessage = ref(false);
  // 状态刷新定时器
  let statusTimer: any;
  // 刷新的类型
  const refreshType = ref();
  // 状态接口请求操作
  async function getStatusReq(inLoop = false) {
    try {
      refreshStatus.value = await statusRefreshApi();
      if (refreshStatus.value && needShowMessage.value === false) needShowMessage.value = true;
      if (refreshStatus.value === false && needShowMessage.value) {
        successCallback(refreshType.value);
      }
      if (!inLoop) {
        getSendStatusLoop();
      }
    } catch (error) {
      refreshStatus.value = false;
      console.log('error', error);
    }
  }
  // 消息发送状态循环生成方法
  function getSendStatusLoop() {
    statusTimer = setInterval(() => {
      if (refreshStatus.value === true) {
        getStatusReq(true);
      } else {
        clearInterval(statusTimer);
        statusTimer = null;
      }
    }, 2000);
  }

  // 开始刷新状态
  function handleStartRefresh(type?: string) {
    refreshType.value = type;
    refreshStatus.value = true;
    needShowMessage.value = true;
    getStatusReq();
    // refresh();
  }

  // 获取状态
  getStatusReq();

  onUnmounted(() => {
    // 清空定时器
    if (statusTimer) {
      clearInterval(statusTimer);
      statusTimer = null;
    }
  });

  return {
    refreshStatus,
    handleStartRefresh
  };
};
